import { Inject, Injectable } from '@nestjs/common';
import { CreateResourceDto } from './dto/create-resource.dto';
import { UpdateResourceDto } from './dto/update-resource.dto';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from '../users/entities/user.entity';
import { Repository } from 'typeorm';
import { Role } from '../role/entities/role.entity';
import { RedisService } from '../redis/redis.service';
import { Resource } from './entities/resource.entity';
import { OssService } from '../oss/oss.service';
import OssConfig from '../config/ossConfig';

@Injectable()
export class ResourceService {
  constructor(
    @InjectRepository(Resource) private readonly resource: Repository<Resource>,
    private readonly ossService: OssService,
  ) {}

  async create(createResourceDto: CreateResourceDto) {
    await this.resource.save(createResourceDto);
    return {
      msg: '创建资源成功',
    };
  }

  async findAll(query) {
    return {
      data: {
        resourceList: await this.resource.find(),
      },
    };
  }

  findOne(id: number) {
    return `This action returns a #${id} resource`;
  }

  async update(id: string, updateResourceDto: UpdateResourceDto) {
    const resource = await this.resource.findOne({
      where: { id },
    });
    if (!resource) {
      return {
        msg: '资源不存在',
        data: false,
      };
    }
    await this.resource.update(id, updateResourceDto);
    return {
      msg: '更新资源成功',
    };
  }

  async remove(id: string) {
    const resource = await this.resource.findOne({
      where: { id },
    });
    if (!resource) {
      return {
        msg: '资源不存在',
        data: false,
      };
    }
    try {
      await this.resource.delete(id);
      return {
        msg: '删除资源成功',
        data: true,
      };
    } catch (err) {
      return {
        msg: '删除资源失败',
        data: false,
      };
    }
  }

  /**
   * 判断文件是否存在
   * @param {string} fileName
   */
  async exists(fileName: string) {
    const exists = await this.resource.findOne({
      where: { url: fileName },
    });
    if (exists) {
      return {
        msg: '文件已存在',
        data: true,
      };
    } else {
      return {
        msg: '文件不存在',
        data: false,
      };
    }
  }
}
